<?php
namespace Home\Controller;
use Think\Controller;
use Think\Controller\RestController;
use Home\Common\Response;
use Home\Common\BizCode;
use Home\Common\ConditionBuilder;
class GoodsController extends RestController {
  private $user;
  public function _initialize(){
    $this->user = session('user');
  }

  public function getSaleDetail(){
    $response = new Response();

    $Dao = D('Product');
    $result = $Dao
      ->join('product_template on product.product_template_id = product_template.product_template_id')
      ->join('product_discount on product_discount.product_id = product.product_id')
      ->where('product.product_id = %d and product.status = "0"', I('product_id'))->find();

    if(!$result){
      $response->setFailState('GOODS_NOT_ON_SALE');
    } else {
      $response->addData('product', $result);
    }

    $this->response($response, 'json');
  }

  // 查询评论总数和平均分
  public function getCommentCountAndCredit(){
    $response = new Response();

    $Dao = M('product_comment');
    $result = $Dao->field('count(*) as count, avg(score) as score')->where('product_id = %d and status = "1"', I('product_id'))->find();

    $response->addData('count', $result['count']);
    $response->addData('score', $result['score']);

    $this->response($response, 'json');
  }

  public function getComment(){
    $response = new Response();

    $num = I('num') < 1? 1 : I('num');
    $page = I('page') < 1? 1 : I('page');

    $Dao = D('ProductComment');
    $result = $Dao->relation('user')->where('product_id = %d and status = "1"', I('product_id'))->select();

    $response->addData('comments', $result);
    $this->response($response, 'json');
  }

  public function getById(){
    $response = new Response();

    $Dao = D('Product');
    $result = $Dao->relation('product_template')->find(I('product_id'));

    $response->addData('product', $result);
    $this->response($response, 'json');
  }
}
